package cn.netty.exemple6;

import cn.netty.exemple6.marshall.MarshallCodeFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class SubReqServer {

    private NioEventLoopGroup acceptorGroup;
    private NioEventLoopGroup workGroup;
    private ServerBootstrap serverBootstrap;

    private void init(){
        acceptorGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(acceptorGroup,workGroup)
                .handler(new LoggingHandler(LogLevel.INFO))
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024);

    }

    public SubReqServer(){
        init();
    }

    /**
     * marshalling 的编解码器自带解决粘包的问题
     * @param port
     * @return
     * @throws InterruptedException
     */
    public ChannelFuture doAcceptor(int port) throws InterruptedException {
        this.serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(MarshallCodeFactory.deCoder());
                ch.pipeline().addLast(MarshallCodeFactory.enCoder());
                ch.pipeline().addLast(new SubReqServerHandle());
            }
        });

        return serverBootstrap.bind(port).sync();
    }

    public void release(){
        this.workGroup.shutdownGracefully();
        this.acceptorGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        SubReqServer server = new SubReqServer();
        ChannelFuture future = null;
        try {
            future = server.doAcceptor(8881);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }finally {
            server.release();
        }
    }

}
